// @ts-ignore
import {
  deleteChartUsingPost,
  listMyChartByPageUsingPost,
} from '@/services/zengjin/chartController';
import { QuestionCircleOutlined, SmileOutlined } from '@ant-design/icons';
import { Button, Card, Col, List, Popconfirm, Result, Row, message } from 'antd';
import ReactECharts from 'echarts-for-react';
import React, { useEffect, useState } from 'react';

const MyChart: React.FC = () => {
  const initSearchParams = {
    current: 1,
    pageSize: 5,
    sortField: 'createTime',
    sortOrder: 'desc',
  };

  const [searchParams, setSearchParams] = useState<API.ChartQueryRequest>({ ...initSearchParams });
  const [chartList, setChartList] = useState<API.Chart[]>();
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  /**
   * 获取数据
   */
  const getDate = async () => {
    setLoading(true);
    try {
      const res = await listMyChartByPageUsingPost(searchParams);
      if (res.data) {
        setChartList(res.data.records ?? []);
        setTotal(res.data.total ?? 0);
        if (res.data.records) {
          res.data.records.forEach((data) => {
            try {
              data.genChart = JSON.parse(data.genChart ?? '{}');
            } catch (e: any) {
              console.log('解析错误：', e);
              message.error('解析错误' + e.message);
              data.genChart = JSON.parse(
                '{\n' + '  "title": {\n' + '    "text": "图表解析错误"\n' + '  }\n' + '}',
              ); // 使用空对象进行解析
            }
          });
        }
      } else {
        message.error('获取图表失败');
      }
    } catch (e: any) {
      message.error('获取数据失败' + e.message);
    }
    setLoading(false);
  };

  /**
   * 删除图表
   */
  const deleteChart = async (deleteParam: number | undefined) => {
    console.log('删除了' + deleteParam);
    setLoading(true);
    const deleteRequest: API.DeleteRequest = { id: deleteParam };
    try {
      const res = await deleteChartUsingPost(deleteRequest);
      if (res.code == 0) {
        message.success('删除成功');
        setTimeout(() => {
          getDate();
        }, 1000);
      } else {
        message.error('删除失败' + res.message);
      }
    } catch (e: any) {
      message.error('删除失败' + e.message);
    }
    setLoading(false);
  };
  /**
   * 钩子函数，首次加载页面的时候运行
   */

  useEffect(() => {
    getDate();
  }, [searchParams]);

  return (
    <div>
      <List
        itemLayout="vertical"
        size="large"
        pagination={{
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              current: page,
              pageSize: pageSize,
            });
          },
          current: searchParams.current,
          pageSize: searchParams.pageSize,
          total: total,
        }}
        loading={loading}
        dataSource={chartList}
        renderItem={(item) => (
          <List.Item key={item.id}>
            <Card title={item.name}>
              <p style={{ marginBottom: 16 }}>分析目标：{item.goal}</p>
              <div style={{ marginBottom: 16 }}>{item.genResult}</div>
              <div>
                <>
                  {item.status === 'succeed' && <ReactECharts option={item.genChart} />},
                  {item.status === 'failed' && (
                    <Result icon={<SmileOutlined />} title={'图表生成失败'} />
                  )}
                  ,
                  {item.status === 'running' && (
                    <Result
                      icon={<SmileOutlined />}
                      title={'图表生成中'}
                      extra={
                        <Button type="primary" onClick={getDate}>
                          刷新
                        </Button>
                      }
                    />
                  )}
                  ,
                  {item.status === 'warning' && (
                    <Result icon={<SmileOutlined />} title={'图表生成排队中'} />
                  )}
                </>
              </div>
              <div>
                <Row gutter={16} justify={'space-between'}>
                  <Col>
                    <span>创建时间：{(item.createTime ?? '').substring(0, 10)}</span>
                  </Col>
                  <Col>
                    <Popconfirm
                      title="删除图表"
                      description="你确定删除这个图表吗?"
                      icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
                      onConfirm={() => deleteChart(item.id)}
                    >
                      <Button type="dashed" danger>
                        删除
                      </Button>
                    </Popconfirm>
                  </Col>
                </Row>
              </div>
            </Card>
          </List.Item>
        )}
      />
    </div>
  );
};

export default MyChart;
